package com.medical.data.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.medical.data.component.TemplateTypeComponent;
import com.medical.data.utils.DozerUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.medical.data.component.LoginUserThreadLocal;
import com.medical.data.constEnum.CommonEnum;
import com.medical.data.constEnum.FormEnum;
import com.medical.data.domain.*;
import com.medical.data.exception.MyException;
import com.medical.data.mapper.FormTemplateMapper;
import com.medical.data.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.data.utils.DateUtil;
import com.medical.data.utils.ResultCode;
import com.medical.data.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cj
 * @since 2024-01-23
 */
@Service
@Slf4j
public class FormTemplateServiceImpl extends ServiceImpl<FormTemplateMapper, FormTemplate> implements FormTemplateService {

    @Autowired
    private TokenSerivce tokenSerivce;

    @Autowired
    private ProjectDataService projectDataService;

    @Autowired
    private ProjectTemplateService projectTemplateService;

    @Autowired
    private TemplateFormService templateFormService;

    @Autowired
    private TemplateTypeComponent templateTypeComponent;

    @Autowired
    private PatientTemplateService patientTemplateService;

    @Autowired
    private PatientService patientService;

    @Autowired
    private FormDataService formDataService;

    @Autowired
    private FormItemService formItemService;

    @Autowired
    private UserPermissionService userPermissionService;

    @Override
    //查询父模版信息
    public IPage<FormTemplate> getFormById(int currentPage) {
        User user = LoginUserThreadLocal.get().getUser();
        if (ObjectUtils.isEmpty(user)) {
            throw new MyException(ResultCode.ERROR.getCode(), "用户不存在");
        }

        Page<FormTemplate> pageQuery = new Page<>(currentPage, 12); // 指定页数和每页记录数
        LambdaQueryWrapper<FormTemplate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FormTemplate::getUserId, user.getId())
                .eq(FormTemplate::getPId, 0);

        return baseMapper.selectPage(pageQuery, lambdaQueryWrapper);
    }

    @Override
    //创建父模版
    public void insertForm(FormVo formVo) {
        User user = LoginUserThreadLocal.get().getUser();
        if (ObjectUtils.isEmpty(user)) {
            throw new MyException(ResultCode.ERROR.getCode(), "用户不存在");
        }

        //把VO中的值与实体类中的变量对应
        FormTemplate template = new FormTemplate();
        template.setUserId(user.getId());
        template.setName(formVo.getName());
        template.setType(formVo.getType());
        template.setPId("0");//父模版没有父id，设置为0
        template.setScheme(JSONObject.toJSONString(formVo.getScheme()));
        template.setStatus(true);//父模版默认不需要填写，为true
        template.setIsAddItem(true);
        template.setIsDelete(false);

        baseMapper.insert(template);
    }

    public void insertFormTemplate(FormVo formVo) {
        User user = LoginUserThreadLocal.get().getUser();
        if (ObjectUtils.isEmpty(user)) {
            throw new MyException(ResultCode.ERROR.getCode(), "用户不存在");
        }

        //把VO中的值与实体类中的变量对应
        FormTemplate template = new FormTemplate();
        template.setId(user.getId());
        template.setName(formVo.getName());
        template.setType(formVo.getType());
        template.setPId(formVo.getPId());//父模版没有父id，设置为0
        template.setScheme(JSONObject.toJSONString(formVo.getScheme()));

        template.setStatus(true);//父模版默认不需要填写，为true
        template.setIsAddItem(true);
        template.setIsDelete(false);


/*        LambdaUpdateWrapper<Tongji>lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Tongji::getFormNumber,);

        baseMapper.insert(template);*/
    }

    @Override
    public List<FormTemplate> getFormByUserId(int currentPage) {
        User user = LoginUserThreadLocal.get().getUser();
        if (ObjectUtils.isEmpty(user)) {
            throw new MyException(ResultCode.ERROR.getCode(), "用户不存在");
        }
        Page<FormTemplate> page = new Page<>(currentPage, 12);
        //查询父模块
        this.baseMapper.selectPage(page, Wrappers.<FormTemplate>lambdaQuery().eq(FormTemplate::getPId, "0")
                .eq(FormTemplate::getUserId, user.getId())
                .orderByDesc(FormTemplate::getCreateTime));
        List<FormTemplate> formTemplates = page.getRecords();
        if (CollectionUtils.isEmpty(formTemplates)) {
            return null;
        }
        //父模块不为空
        formTemplates.forEach(item -> {
            List<FormTemplate> formTemplates1 = this.baseMapper.selectList(Wrappers.<FormTemplate>lambdaQuery().eq(FormTemplate::getPId, item.getId())
                    .eq(FormTemplate::getUserId, user.getId())
                    .orderByDesc(FormTemplate::getCreateTime));
            item.setChildrenFormTemplate(formTemplates1);
        });
        return formTemplates;
    }

    @Override
    public void createNode(NodeVo nodeVo) {
        userPermissionService.getFormPermission(nodeVo.getProjectId());
        User user = tokenSerivce.getUser();
        FormTemplate formTemplate = new FormTemplate();
        formTemplate.setUserId(user.getId());
        //首先查询项目是否存在,是否已经结束
        ProjectData project = projectDataService.getById(nodeVo.getProjectId());
        if (ObjectUtils.isEmpty(project)) {
            throw new MyException(ResultCode.ERROR.getCode(), "项目不存在");
        }
        Date endTime = project.getEndTime();
        if (DateUtil.compareDateAndTime(new Date(), endTime)) {
            throw new MyException(ResultCode.ERROR.getCode(), "项目已结束");
        }
        //新增节点
        //1.查询该节点是否存在
        Integer templateNodeCount = baseMapper.isTemplateNode(nodeVo);
        if (templateNodeCount != 0) {
            throw new MyException(ResultCode.ERROR.getCode(), "该节点已存在");
        }
        //2.1新增非随访节点到模版表里面
        if (!nodeVo.getIsFollow()) {
            formTemplate.setName(nodeVo.getTemplateName()).setTemplateDesc(nodeVo.getTemplateDesc())
                    .setPId(FormEnum.NODE.getPid())
                    .setStatus(FormEnum.NODE.getStatus())
                    .setIsAddItem(FormEnum.NODE.getIsAddItem())
                    .setType(FormEnum.NODE.getType())
                    .setIsFollowUp(false)
                    .setBuildStatus("0");
        }

        //2.2新增随访节点到模版表里面
        else {
            formTemplate.setName(nodeVo.getTemplateName())
                    .setTemplateDesc(nodeVo.getTemplateDesc())
                    .setPId(FormEnum.NODE.getPid())
                    .setStatus(FormEnum.NODE.getStatus())
                    .setIsAddItem(FormEnum.NODE.getIsAddItem())
                    .setType(FormEnum.NODE.getType())
                    .setBuildStatus("0")
                    .setIsFollowUp(true)
                    .setFollowUpTime(nodeVo.getFollowUpTime());
        }
        int insert = baseMapper.insert(formTemplate);
        if (insert < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "节点添加失败");
        //更新中间表
        ProjectTemplate projectTemplate = new ProjectTemplate()
                .setProjectId(nodeVo.getProjectId())
                .setFormTemplateId(formTemplate.getId());
        boolean save = projectTemplateService.save(projectTemplate);
        if (!save)
            throw new MyException(ResultCode.ERROR.getCode(), "节点添加失败");

    }

    @Override
    public FormTemplate creatFormByNode(FormNodeVo formNodeVo) {
        userPermissionService.getFormPermission(formNodeVo.getProjectId());

        User user = tokenSerivce.getUser();
        FormTemplate formTemplate = new FormTemplate();
        formTemplate.setUserId(user.getId());
        //同一个节点下不允许有相同名字的节点
        LambdaQueryWrapper<FormTemplate> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(FormTemplate::getPId, formNodeVo.getNodeId())
                .eq(FormTemplate::getName, formNodeVo.getTemplateName());
        FormTemplate formTemplate3 = this.baseMapper.selectOne(wrapper1);
        if (ObjectUtils.isNotEmpty(formTemplate3)) {
            throw new MyException(ResultCode.ERROR.getCode(), "该表单在此节点中已存在");
        }
        //首先查询项目是否存在,是否已经结束
        ProjectData project = projectDataService.getById(formNodeVo.getProjectId());
        if (ObjectUtils.isEmpty(project)) {
            throw new MyException(ResultCode.ERROR.getCode(), "项目不存在");
        }
        Date endTime = project.getEndTime();
        if (DateUtil.compareDateAndTime(new Date(), endTime)) {
            throw new MyException(ResultCode.ERROR.getCode(), "项目已结束");
        }
        //查询节点是否存在
        FormTemplate formTemplate1 = baseMapper.selectById(formNodeVo.getNodeId());
        if (ObjectUtils.isEmpty(formTemplate1)) {
            throw new MyException(ResultCode.ERROR.getCode(), "节点不存在");
        }
        Integer isTemplateFormCount = baseMapper.isTemplateForm(formNodeVo);
        log.info("========>{}", isTemplateFormCount);
/*        if (false) {
            throw new MyException(ResultCode.ERROR.getCode(), "该节点下表单已存在");
        }*/
        //2.新增节点到模版表里面
        formTemplate.setName(formNodeVo.getTemplateName());
        formTemplate.setTemplateDesc(formNodeVo.getTemplateDesc());
        formTemplate.setPId(formNodeVo.getNodeId());
        formTemplate.setStatus(FormEnum.Form.getStatus());
        formTemplate.setIsAddItem(FormEnum.Form.getIsAddItem());
        formTemplate.setType(FormEnum.Form.getType());
        formTemplate.setBuildStatus("0");
        int insert = baseMapper.insert(formTemplate);
        if (insert < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "表单添加失败");
        //更新中间表，只有从节点里面添加的时候才更新中间表
        TemplateForm templateForm = new TemplateForm()
                .setProjectId(formNodeVo.getProjectId())
                .setNodeId(formNodeVo.getNodeId())
                .setFormId(formTemplate.getId());
        boolean save = templateFormService.save(templateForm);
        if (!save)
            throw new MyException(ResultCode.ERROR.getCode(), "表单添加失败");
        //获取表单信息
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, formTemplate.getId());

        FormTemplate formTemplate2 = baseMapper.selectOne(wrapper);
        //查看项目下有没有患者
        if (patientService.isExistInProject(formNodeVo.getProjectId())) {
            //更新患者节点关系表
            patientTemplateService.updateNoFinish(formNodeVo.getProjectId(), formNodeVo.getNodeId(), formTemplate.getId());
        }
        return formTemplate2;
    }

    @Override
    public FormTemplate createForm(FormByFormTamplate formByFormTamplate) {
        //从表单管理创建表单
        User user = tokenSerivce.getUser();
        //首先查询是否存在相同的名字的表单模块
        FormTemplate formTemplate = baseMapper.selectOne(Wrappers.<FormTemplate>lambdaQuery()
                .eq(FormTemplate::getName, formByFormTamplate.getTemplateName())
                .eq(FormTemplate::getBuildStatus, CommonEnum.ONE.getCommonEnum())
                .eq(FormTemplate::getUserId, user.getId()));
        if (!ObjectUtils.isEmpty(formTemplate)) {
            throw new MyException(ResultCode.ERROR.getCode(), "该表单已存在");
        }
        //添加表单
        FormTemplate formTemplate1 = new FormTemplate();
        formTemplate1.setUserId(user.getId());
        //2.新增节点到模版表里面
        formTemplate1.setName(formByFormTamplate.getTemplateName())
                .setTemplateDesc(formByFormTamplate.getTemplateDesc())
                .setPId(FormEnum.Form.getPid())
                .setStatus(FormEnum.Form.getStatus())
                .setIsAddItem(FormEnum.Form.getIsAddItem())
                .setType(FormEnum.Form.getType())
                .setBuildStatus("1");
        int insert = baseMapper.insert(formTemplate1);
        if (insert < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "表单添加失败");
        //获取表单信息
        FormTemplate formTemplate2 = baseMapper.selectById(formTemplate1.getId());
        return formTemplate2;
    }

    @Override
    public List<FormResultVo> getAllForm(AllFormVo allFormVo) {
        userPermissionService.getFormPermission(allFormVo.getProjectId());

        User user = tokenSerivce.getUser();
        //获取节点下的表单
        List<String> ids = new ArrayList<>();
        List<FormResultVo> formResultVos = new ArrayList<>();
        //从节点与表单中间表进行查询
        ids = templateFormService.getTemplateForm(allFormVo);
        //剔除当前节点下的表单
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(FormTemplate::getBuildStatus, "1");

        //wrapper.eq(FormTemplate::getPId,CommonEnum.ZERO.getCommonEnum());
        if (!CollectionUtils.isEmpty(ids)) {
            wrapper.notIn(FormTemplate::getId, ids);
        }
        wrapper.eq(FormTemplate::getUserId, user.getId());//TODO 后续需要进行商量是否需要
        if (CommonEnum.ZERO.getCommonEnum().equals(allFormVo.getIsFormOrFollwoUp())) {
            wrapper.eq(FormTemplate::getType, FormEnum.Form.getType());//表示表单
        }
        if (CommonEnum.ONE.getCommonEnum().equals(allFormVo.getIsFormOrFollwoUp())) {
            wrapper.eq(FormTemplate::getType, FormEnum.FOLLOWUP.getType());//表示随访表单
        }
        List<FormTemplate> formTemplates = baseMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(formTemplates)) {
            formResultVos = DozerUtils.mapList(formTemplates, FormResultVo.class);
        }
        return formResultVos;
    }

    @Override
    public void importForm(ImportFormVo importFormVo) {
        userPermissionService.getFormPermission(importFormVo.getProjectId());
        //不允许导入同名表单
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, importFormVo.getFormId())
                .eq(FormTemplate::getBuildStatus, true);
        FormTemplate formTemplate = this.baseMapper.selectOne(wrapper);
        String name = formTemplate.getName();

        LambdaQueryWrapper<FormTemplate> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(FormTemplate::getPId, importFormVo.getNodeId())
                .eq(FormTemplate::getName, name)
                .eq(FormTemplate::getBuildStatus, false);

        FormTemplate formTemplate1 = this.baseMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(formTemplate1)) {
            throw new MyException(ResultCode.ERROR.getCode(), "不能导入同名表单");
        }
        //TODO 修改导入表单的逻辑，应该复制表单的模版，而不是直接把表单导入，不然多个项目导入同个表单会导致填写数据异常
        FormTemplate formTemplate2 = new FormTemplate();
        // 手动复制非自动生成和非默认填充的属性
        formTemplate2.setUserId(formTemplate.getUserId());
        formTemplate2.setName(formTemplate.getName());
        formTemplate2.setPId(importFormVo.getNodeId());
        formTemplate2.setType(formTemplate.getType());
        formTemplate2.setScheme(formTemplate.getScheme());
        formTemplate2.setStatus(false);
        formTemplate2.setIsAddItem(formTemplate.getIsAddItem());
        formTemplate2.setTemplateDesc(formTemplate.getTemplateDesc());
        formTemplate2.setBuildStatus("0");
        formTemplate2.setIsFollowUp(formTemplate.getIsFollowUp());
        formTemplate2.setFollowUpTime(formTemplate.getFollowUpTime());
        int insert = this.baseMapper.insert(formTemplate2);
        if (insert < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "导入失败");
        }

        //首先查询是否已经导入到数据库中
        long count = templateFormService.count(Wrappers.<TemplateForm>lambdaQuery().eq(TemplateForm::getFormId, importFormVo.getFormId())
                .eq(TemplateForm::getProjectId, importFormVo.getProjectId())
                .eq(TemplateForm::getNodeId, importFormVo.getNodeId()));
        if (count > 0)
            throw new MyException(ResultCode.ERROR.getCode(), "该表单已导入到该节点中");
        TemplateForm templateForm = new TemplateForm().setFormId(formTemplate2.getId()).setNodeId(formTemplate2.getPId())
                .setProjectId(importFormVo.getProjectId());
        boolean save = templateFormService.save(templateForm);
        if (!save)
            throw new MyException(ResultCode.ERROR.getCode(), "导入失败");

        //项目下面有患者时才更新，更新患者节点关系表
        if (patientService.isExistInProject(importFormVo.getProjectId())) {
            patientTemplateService.updateNoFinish(importFormVo.getProjectId(), importFormVo.getNodeId(), formTemplate2.getId());
        }
        //TODO 接着负责表单下面的每一个组件
        //1.先找出来所有组件
        //2.然后重新生成组件id,其他的全部一样
        List<FormItem> list = formItemService.getFormItemByFormId(importFormVo.getFormId());
        list.forEach(formItem -> {
            FormItem formItem1 = new FormItem();
            formItem1.setFormTemplateId(formItem.getFormTemplateId())
                    .setFormItemId(formItem.getFormItemId())
                    .setFormId(formTemplate2.getId())
                    .setLabel(formItem.getLabel())
                    .setItemType(formItem.getItemType())
                    .setRequired(formItem.getRequired())
                    .setPlaceholder(formItem.getPlaceholder())
                    .setRegList(formItem.getRegList())
                    .setDefaultValue(formItem.getDefaultValue())
                    .setShowLabel(formItem.getShowLabel())
                    .setIsHideType(formItem.getIsHideType())
                    .setIsSpecialType(formItem.getIsSpecialType())
                    .setConfig(formItem.getConfig())
                    .setSpan(formItem.getSpan())
                    .setSort(formItem.getSort())
                    .setItemType(formItem.getItemType())
                    .setCompType(formItem.getCompType())
                    .setLabel(formItem.getLabel())
                    .setPlaceholder(formItem.getPlaceholder())
                    .setScheme(formItem.getScheme())
                    .setRequired(formItem.getRequired());
            long currentTimeMillis = Instant.now().toEpochMilli();
            String oneItemId = "fd_" + currentTimeMillis;
            formItem1.setOneItemId(oneItemId);
            formItemService.addAllFormItem(formItem1);
        });
    }

    @Override
    public void deleteForm(String formId) {

        int i = baseMapper.deleteById(formId);
        if (i < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "删除表单失败");
        //删除中间表
        boolean remove = templateFormService.remove(Wrappers.<TemplateForm>lambdaQuery().eq(TemplateForm::getFormId, formId));
        if (!remove)
            throw new MyException(ResultCode.ERROR.getCode(), "删除表单失败");
    }

    @Override
    public void updateForm(UpdateFormVo updateForm) {
        //查询该用户下是否有一样的模版名字
        User user = tokenSerivce.getUser();
        List<FormTemplate> formTemplates = baseMapper.selectList(Wrappers.<FormTemplate>lambdaQuery().eq(FormTemplate::getUserId, user.getId())
                .eq(FormTemplate::getName, updateForm.getFormName()).select(FormTemplate::getId).last("limit 1"));
        if (!CollectionUtils.isEmpty(formTemplates)) {
            throw new MyException(ResultCode.ERROR.getCode(), "该表单名字已存在");
        }
        int update = baseMapper.update(new FormTemplate().setId(updateForm.getFormId()).setName(updateForm.getFormName()), Wrappers.<FormTemplate>lambdaUpdate().eq(FormTemplate::getId, updateForm.getFormId()));
        if (update < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "表单修改失败");
    }

    @Override
    public List<FormResultVo> getFormByNode(String nodeId, String projectId) {
        userPermissionService.getFormPermission(projectId);
        List<FormResultVo> formResultVos = new ArrayList<>();
        formResultVos = baseMapper.getFormByNode(nodeId, projectId);
        return formResultVos;
    }

    @Override
    public Map<String, Object> getFormByUser(QueryFormVo queryFormVo) {
        User user = tokenSerivce.getUser();
        Integer current = CommonEnum.OTHER_FORM_CURRENT.getValue();
        Integer limit = CommonEnum.OTHER_FORM_LIMIT.getValue();
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        //做分页
        if (!ObjectUtils.isEmpty(queryFormVo)) {
            if (StringUtils.isNotBlank(queryFormVo.getFormName())) {
                wrapper.like(FormTemplate::getName, queryFormVo.getFormName());
            }
            if (!ObjectUtils.isEmpty(queryFormVo.getBeginTime())) {
                wrapper.ge(FormTemplate::getCreateTime, queryFormVo.getBeginTime());
            }
            if (!ObjectUtils.isEmpty(queryFormVo.getEndTime())) {
                wrapper.le(FormTemplate::getCreateTime, queryFormVo.getEndTime());
            }
            if (!ObjectUtils.isEmpty(queryFormVo.getCurrent())) {
                current = queryFormVo.getCurrent();
            }
            if (!ObjectUtils.isEmpty(queryFormVo.getLimit())) {
                limit = queryFormVo.getLimit();
            }
        }
        wrapper.eq(FormTemplate::getUserId, user.getId());
        wrapper.orderByDesc(FormTemplate::getCreateTime, FormTemplate::getName);
        wrapper.eq(FormTemplate::getBuildStatus, "1");
        wrapper.notIn(FormTemplate::getType, CommonEnum.ZERO.getCommonEnum());
        Page<FormTemplate> page = new Page<>(current, limit);
        baseMapper.selectPage(page, wrapper);
        List<FormTemplate> formTemplates = page.getRecords();
        List<FormResultVo> formResultVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(formTemplates)) {
            formResultVos = DozerUtils.mapList(formTemplates, FormResultVo.class);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("current", page.getCurrent());
        map.put("formResultVos", formResultVos);
        return map;
    }

    @Override
    public void savaForm(SavaFormVo savaFormVo) {
        //获取类型
        String type = savaFormVo.getType();
        Map<String, FormTemplateType> formTemplateTypeMap = templateTypeComponent.get();
        if (!ObjectUtils.isEmpty(formTemplateTypeMap)) {
            if (ObjectUtils.isEmpty(formTemplateTypeMap.get(type))) {
                throw new MyException(ResultCode.ERROR.getCode(), "没有该类型的表单");
            }
        } else {
            throw new MyException(ResultCode.ERROR.getCode(), "请新增表单类型");
        }
        //新增
        FormTemplate formTemplate = new FormTemplate();
        BeanUtils.copyProperties(savaFormVo, formTemplate);
        int i = baseMapper.updateById(formTemplate);
        if (i < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "保存失败");
    }


    //根据formID判断是否存在该模版
    public void isExist(String formId) {
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, formId);
        FormTemplate formTemplate = baseMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(formTemplate)) {
            throw new MyException(ResultCode.ERROR.getCode(), "该模版不存在或id错误");
        }
    }

    @Override
    public List<FormTemplate> getFormByIds(List<String> value) {
        List<FormTemplate> formTemplates = new ArrayList<>();
        if (value.size() != 0) {
            formTemplates = baseMapper.selectList(Wrappers.<FormTemplate>lambdaQuery().in(FormTemplate::getId, value).orderByDesc(FormTemplate::getCreateTime));
        }
        return formTemplates;
    }

    @Override
    public List<AllFormsVo> getAllFormByProjectId(String projectId) {
        List<AllFormsVo> list = new ArrayList<>();
        List<FormTemplate> formTemplates = projectTemplateService.getAllNodes(projectId);
        int n = 0;
        for (FormTemplate formTemplate : formTemplates) {

            String nodeId = formTemplate.getId();
            String nodeName = formTemplate.getName();

            List<FormResultVo> formResultVos = this.baseMapper.getFormByNode(nodeId, projectId);
            // 创建一个内部Map来存储表单结果数据
            Map<String, Object> formDataMap = new LinkedHashMap<>();
            formDataMap.put("nodeId", nodeId);
            formDataMap.put("nodeName", nodeName);
            formDataMap.put("formResults", formResultVos);
            list.add(new AllFormsVo().setFormResultVos(formResultVos).setNodeName(nodeName).setNodeId(nodeId));
        }
        return list;
    }

    @Override
    public boolean isFollowUp(String nodeId) {
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, nodeId);
        FormTemplate formTemplate = this.baseMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(formTemplate)) {
            throw new MyException(ResultCode.ERROR.getCode(), "未找到改节点");
        }

        return formTemplate.getIsFollowUp();
    }

    @Override
    public String getNameByNodeId(String nodeId) {
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, nodeId);
        return this.baseMapper.selectOne(wrapper).getName();
    }

    @Override
    public FormTemplate getNodeById(String nodeId) {
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, nodeId);
        FormTemplate formTemplate = this.baseMapper.selectOne(wrapper);
        return formTemplate;
    }

    @Override
    public int getFormTemplateNumber() {
        User user = tokenSerivce.getUser();
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getUserId, user.getId())
                .eq(FormTemplate::getBuildStatus, true);
        return this.baseMapper.selectList(wrapper).size();

    }

    @Override
    public int getTodayFormTemplateNumber() {
        User user = tokenSerivce.getUser();
        LocalDate today = LocalDate.now();

        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getUserId, user.getId())
                .eq(FormTemplate::getBuildStatus, true)
                .apply("DATE(create_time) = DATE({0})", today); // 使用DATE()函数比较日期部分;
        return this.baseMapper.selectList(wrapper).size();
    }

    @Override
    public void deleteNode(String nodeId) {
        userPermissionService.getFormPermission(projectTemplateService.getProjectIdByNodeId(nodeId));
        //1.在节点表里删除
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, nodeId);
        int delete = this.baseMapper.delete(wrapper);
        if (delete < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "删除节点失败");
        }
        //2.在项目节点表里删除
        projectTemplateService.deleteNodeById(nodeId);
        //3.在表单数据表里删除
        formDataService.deleteDateByNodeId(nodeId);
        //4.在节点表单表里删除
        templateFormService.deleteNodeById(nodeId);
        //5.在患者节点表里删除
        patientTemplateService.deleteNodeById(nodeId);
        //在用户表中删除
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId, nodeId);
    }

    @Override
    public void deleteFormInNode(String formId) {
        String projectId = projectTemplateService.getProjectIdByNodeId(templateFormService.getNodeIdByFormId(formId));
        userPermissionService.getFormPermission(projectId);
        //1.删除表单模版表数据
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, formId);

        FormTemplate formTemplate = this.baseMapper.selectOne(wrapper);
        //通过导入的不删除，只删除它和节点的关系
        if (formTemplate.getBuildStatus().equals("0")) {
            int delete = this.baseMapper.delete(wrapper);
            if (delete < 1) {
                throw new MyException(ResultCode.ERROR.getCode(), "删除表单失败");
            }
        }
        //2.删除节点表单数据
        templateFormService.deleteFormById(formId);
        //3.删除表单数据表数据
        formDataService.deleteDataByFormId(formId);
        //4.更新患者节点表中的完成与未完成的字段
        patientTemplateService.updateFormStatus(formTemplate.getPId(), formId);


    }

    @Override
    public void deleteFormInModel(String formId) {
        //1.删除表单模版表数据
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, formId)
                .eq(FormTemplate::getBuildStatus, "1");

        FormTemplate formTemplate = this.baseMapper.selectOne(wrapper);

        int delete = this.baseMapper.delete(wrapper);
        if (delete < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "删除表单失败");
        }

        //2.删除节点表单数据
        templateFormService.deleteFormById(formId);
        //3.删除表单数据表数据
        formDataService.deleteDataByFormId(formId);
        //4.更新患者节点表中的完成与未完成的字段
        patientTemplateService.updateFormStatus(formTemplate.getPId(), formId);
    }

    @Override
    public int getFormDataNumberByUser(String id) {
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getUserId, id)
                .eq(FormTemplate::getBuildStatus, "1");

        return this.baseMapper.selectList(wrapper).size();

    }

    @Override
    public void changeFormMessage(String formId, String newName) {
        String projectId = projectTemplateService.getProjectIdByNodeId(templateFormService.getNodeIdByFormId(formId));
        userPermissionService.getFormPermission(projectId);
        // 创建查询条件，检查表单是否存在
        LambdaQueryWrapper<FormTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FormTemplate::getId, formId);

        // 查询表单
        FormTemplate formTemplate = this.baseMapper.selectOne(queryWrapper);

        // 检查表单是否找到
        if (formTemplate == null) {
            throw new MyException(ResultCode.ERROR.getCode(), "表单不存在");
        }

        // 构建更新条件及设置新名称
        LambdaUpdateWrapper<FormTemplate> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(FormTemplate::getId, formId);

        // 更新表单名称
        formTemplate.setName(newName); // 假设setFormName是用于设置表单名称的方法

        // 执行更新操作
        int rowsAffected = this.baseMapper.update(formTemplate, updateWrapper);

        // 检查更新是否成功
        if (rowsAffected == 0) {
            throw new MyException(ResultCode.ERROR.getCode(), "更新表单名称失败");
        }
    }

    @Override
    public void shareFormTemplate(String formId) {
        String projectId = projectTemplateService.getProjectIdByNodeId(templateFormService.getNodeIdByFormId(formId));
        userPermissionService.getFormPermission(projectId);

        User user = tokenSerivce.getUser();
        //TODO 首先找到要分享的在项目中的表单，判断他的名字在表单广场中是否存在，然后新建一个对象，复制他的样式插入表单广场中
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, formId);
        FormTemplate formTemplate = this.baseMapper.selectOne(wrapper);
        if (formTemplate == null) {
            throw new MyException(ResultCode.ERROR.getCode(), "表单不存在");
        }
        LambdaQueryWrapper<FormTemplate> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(FormTemplate::getName, formTemplate.getName())
                .eq(FormTemplate::getBuildStatus, "1");
        if (this.baseMapper.selectList(wrapper1).size() > 0) {
            throw new MyException(ResultCode.ERROR.getCode(), "改表单名称已在共享表单中存在");
        }
        FormTemplate formTemplate1 = new FormTemplate();
        formTemplate1.setPId("0").setScheme(formTemplate.getScheme()).setBuildStatus("1").setName(formTemplate.getName()).setUserId(user.getId()).setType("1");
        int insert = this.baseMapper.insert(formTemplate1);
        if (insert < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "共享失败");
        }
        //TODO 更新表单组件
        formItemService.shareFormItem(formTemplate.getId(), formTemplate1.getId());
    }

    @Override
    public String getFormStatus(String formId) {
        LambdaQueryWrapper<FormTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FormTemplate::getId, formId);
        return this.baseMapper.selectOne(wrapper).getBuildStatus();
    }
}
